class MainStage extends egret.DisplayObjectContainer {

    private joystick: Joystick;
    private olivier: player.Olivier;

    private desertUrl: string = "resource/tiled/desert/desert.tmx";

    private desertTileMap: tiled.TMXTilemap;

    constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    onAddToStage() {
        this.removeEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
        // let sky = BitmapUtils.createBitmapByName("bg_jpg");
        // this.addChild(sky);
        // let stageW = this.stage.stageWidth;
        // let stageH = this.stage.stageHeight;
        // sky.width = stageW;
        // sky.height = stageH;

        let request = new egret.HttpRequest();
        request.once(egret.Event.COMPLETE, this.onTiledLoaded, this);
        /*发送请求*/
        request.open(this.desertUrl, egret.HttpMethod.GET);
        request.send();
    }

    private onTiledLoaded(event: egret.Event) {
        /*获取到地图数据*/
        let data: any = egret.XML.parse(event.currentTarget.response);
        /*初始化地图*/
        this.desertTileMap = new tiled.TMXTilemap(2000, 2000, data, this.desertUrl);
        this.desertTileMap.render();
        /*将地图添加到显示列表*/
        this.addChild(this.desertTileMap);

        this.olivier = new player.Olivier();
        this.olivier.x = this.stage.stageWidth / 2 - this.olivier.width / 2;
        this.olivier.y = this.stage.stageHeight / 2 - this.olivier.height / 2;
        this.addChild(this.olivier);

        this.touchEnabled = true;
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin, this);
        this.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this);
        this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this);

        this.joystick = new Joystick();
        this.joystick.addEventListener(MoveEvent.MOVE, this.olivier.onMove, this.olivier);
        this.joystick.addEventListener(MoveEvent.MOVE, this.onMoveTiled, this);
    }

    private onMoveTiled(e: MoveEvent) {
        this.desertTileMap.x += 5;
    }

    private onTouchBegin(e: egret.TouchEvent) {
        this.addChild(this.joystick);
        this.joystick.locate(e.localX, e.localY);
    }

    private onTouchMove(e: egret.TouchEvent) {
        this.joystick.move(e.localX, e.localY);
    }

    private onTouchEnd() {
        this.removeChild(this.joystick);
        this.olivier.idle();
    }
}